package com.css.zfzx.sjcj.modules.hddcGeomorphySvyRegion.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import com.css.zfzx.sjcj.common.spacedata.vo.SpaceDataParamsVo;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcGeomorphySvyRegion.repository.HddcGeomorphysvyregionNativeRepository;
import com.css.zfzx.sjcj.modules.hddcGeomorphySvyRegion.repository.HddcGeomorphysvyregionRepository;
import com.css.zfzx.sjcj.modules.hddcGeomorphySvyRegion.repository.entity.HddcGeomorphysvyregionEntity;
import com.css.zfzx.sjcj.modules.hddcGeomorphySvyRegion.service.HddcGeomorphysvyregionService;
import com.css.zfzx.sjcj.modules.hddcGeomorphySvyRegion.viewobjects.HddcGeomorphysvyregionQueryParams;
import com.css.zfzx.sjcj.modules.hddcGeomorphySvyRegion.viewobjects.HddcGeomorphysvyregionVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author zyb
 * @date 2020-11-27
 */
@Service
public class HddcGeomorphysvyregionServiceImpl implements HddcGeomorphysvyregionService {

	@Autowired
    private HddcGeomorphysvyregionRepository hddcGeomorphysvyregionRepository;
    @Autowired
    private HddcGeomorphysvyregionNativeRepository hddcGeomorphysvyregionNativeRepository;

    @Override
    public JSONObject queryHddcGeomorphysvyregions(HddcGeomorphysvyregionQueryParams queryParams, int curPage, int pageSize,String sort,String order) {
        Page<HddcGeomorphysvyregionEntity> hddcGeomorphysvyregionPage = this.hddcGeomorphysvyregionNativeRepository.queryHddcGeomorphysvyregions(queryParams, curPage, pageSize, sort, order);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(hddcGeomorphysvyregionPage);
        return jsonObject;
    }


    @Override
    public HddcGeomorphysvyregionEntity getHddcGeomorphysvyregion(String id) {
        HddcGeomorphysvyregionEntity hddcGeomorphysvyregion = this.hddcGeomorphysvyregionRepository.findById(id).orElse(null);
         return hddcGeomorphysvyregion;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcGeomorphysvyregionEntity saveHddcGeomorphysvyregion(HddcGeomorphysvyregionEntity hddcGeomorphysvyregion) {
        String uuid = UUIDGenerator.getUUID();
        hddcGeomorphysvyregion.setUuid(uuid);
        hddcGeomorphysvyregion.setCreateUser(PlatformSessionUtils.getUserId());
        hddcGeomorphysvyregion.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        hddcGeomorphysvyregion.setIsValid("1");
        hddcGeomorphysvyregion.setQualityinspectionStatus("0");
        hddcGeomorphysvyregion.setExtends10("1");
        this.hddcGeomorphysvyregionRepository.save(hddcGeomorphysvyregion);
        return hddcGeomorphysvyregion;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Iterable<HddcGeomorphysvyregionEntity> saveHddcGeomorphysvyregionList(List<HddcGeomorphysvyregionEntity> list) {
        for (HddcGeomorphysvyregionEntity hddcGeomorphysvyregion : list) {
            String uuid = UUIDGenerator.getUUID();
            hddcGeomorphysvyregion.setUuid(uuid);
            hddcGeomorphysvyregion.setCreateUser(PlatformSessionUtils.getUserId());
            hddcGeomorphysvyregion.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
            hddcGeomorphysvyregion.setIsValid("1");
            hddcGeomorphysvyregion.setQualityinspectionStatus("0");
            hddcGeomorphysvyregion.setExtends10("1");
        }
        return hddcGeomorphysvyregionNativeRepository.batchSave(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcGeomorphysvyregionEntity updateHddcGeomorphysvyregion(HddcGeomorphysvyregionEntity hddcGeomorphysvyregion) {
        HddcGeomorphysvyregionEntity entity = hddcGeomorphysvyregionRepository.findById(hddcGeomorphysvyregion.getUuid()).get();
        UpdateUtil.copyNullProperties(entity,hddcGeomorphysvyregion);
        hddcGeomorphysvyregion.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcGeomorphysvyregion.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcGeomorphysvyregionRepository.save(hddcGeomorphysvyregion);
        return hddcGeomorphysvyregion;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcGeomorphysvyregions(List<String> ids) {
        List<HddcGeomorphysvyregionEntity> hddcGeomorphysvyregionList = this.hddcGeomorphysvyregionRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcGeomorphysvyregionList) && hddcGeomorphysvyregionList.size() > 0) {
            for(HddcGeomorphysvyregionEntity hddcGeomorphysvyregion : hddcGeomorphysvyregionList) {
                hddcGeomorphysvyregion.setIsValid("0");
                hddcGeomorphysvyregion.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcGeomorphysvyregion.setUpdateTime(new Date());
                this.hddcGeomorphysvyregionRepository.save(hddcGeomorphysvyregion);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public void exportFile(HddcGeomorphysvyregionQueryParams queryParams, HttpServletResponse response) {
        List<HddcGeomorphysvyregionEntity> yhDisasterEntities = hddcGeomorphysvyregionNativeRepository.exportYhDisasters(queryParams);
        List<HddcGeomorphysvyregionVO> list=new ArrayList<>();
        for (HddcGeomorphysvyregionEntity entity:yhDisasterEntities) {
            HddcGeomorphysvyregionVO yhDisasterVO=new HddcGeomorphysvyregionVO();
            BeanUtils.copyProperties(entity,yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list, "微地貌测量面-面", "微地貌测量面-面", HddcGeomorphysvyregionVO.class, "微地貌测量面-面.xls", response);
    }

    @Override
    public String exportExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<HddcGeomorphysvyregionVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcGeomorphysvyregionVO.class, params);
            List<HddcGeomorphysvyregionVO> list = result.getList();
            // Excel条数据
            int firstList = list.size();
            StringBuilder sb = new StringBuilder();
            //保存
            saveDisasterList(list, sb);
            returnMsg.append("成功导入" + (result.getList().size() ));
            returnMsg.append(sb);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<HddcGeomorphysvyregionVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    HddcGeomorphysvyregionVO yhDisasterVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + yhDisasterVO.getRowNum() + "行" + yhDisasterVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {

            return "导入失败，请检查数据正确性";
        }
    }
    /**
     * 批量存入库表并且返回错误数量
     *
     * @param list
     * @param message
     * @return
     */
    public void saveDisasterList( List<HddcGeomorphysvyregionVO> list, StringBuilder message) {
        for (int i = 0; i < list.size(); i++) {
            HddcGeomorphysvyregionEntity yhDisasterEntity = new HddcGeomorphysvyregionEntity();
            HddcGeomorphysvyregionVO yhDisasterVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(yhDisasterVO, yhDisasterEntity);
            saveHddcGeomorphysvyregion(yhDisasterEntity);
        }
    }
    @Override
    public void deleteByProjectId(List<String> projectIds) {
        List<HddcGeomorphysvyregionEntity> hddcGeomorphysvyregionList = this.hddcGeomorphysvyregionRepository.queryHddcGeomorphysvyregionsByProjectId(projectIds);
        if(!PlatformObjectUtils.isEmpty(hddcGeomorphysvyregionList) && hddcGeomorphysvyregionList.size() > 0) {
            for(HddcGeomorphysvyregionEntity hddcGeomorphysvyregion : hddcGeomorphysvyregionList) {
                hddcGeomorphysvyregion.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcGeomorphysvyregion.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcGeomorphysvyregion.setIsValid("0");
                this.hddcGeomorphysvyregionRepository.save(hddcGeomorphysvyregion);
            }
        }
    }

    @Override
    public void deleteByTaskId(List<String> taskIds) {
        List<HddcGeomorphysvyregionEntity> hddcGeomorphysvyregionList = this.hddcGeomorphysvyregionRepository.queryHddcGeomorphysvyregionsByTaskId(taskIds);
        if(!PlatformObjectUtils.isEmpty(hddcGeomorphysvyregionList) && hddcGeomorphysvyregionList.size() > 0) {
            for(HddcGeomorphysvyregionEntity hddcGeomorphysvyregion : hddcGeomorphysvyregionList) {
                hddcGeomorphysvyregion.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcGeomorphysvyregion.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcGeomorphysvyregion.setIsValid("0");
                this.hddcGeomorphysvyregionRepository.save(hddcGeomorphysvyregion);
            }
        }
    }

    @Override
    public String judegeParams(String[] datas) {
        String str = "";
        Set<String> set = new HashSet<String>(Arrays.asList(datas));
        if(!set.contains("ID")){
            str+="ID,";
        }
        if(!set.contains("GeomorphySvyPrjID\n")){
            str+="GeomorphySvyPrjID\n,";
        }
        if(!set.contains("FieldID")){
            str+="FieldID,";
        }
        if(!set.contains("Name")){
            str+="Name,";
        }
        if(!set.contains("Profile_AIID")){
            str+="Profile_AIID,";
        }
        if(!set.contains("Profile_ARWID")){
            str+="Profile_ARWID,";
        }
        if(!set.contains("Photo_AIID")){
            str+="Photo_AIID,";
        }
        if(!set.contains("Photo_ARWID")){
            str+="Photo_ARWID,";
        }
        if(!set.contains("PhotoViewingTo")){
            str+="PhotoViewingTo,";
        }
        if(!set.contains("Photographer")){
            str+="Photographer,";
        }
        if(!set.contains("CommentInfo")){
            str+="CommentInfo,";
        }
        return str;
    }

    private String getStrBySourceStr(String source){
        if(StringUtils.isEmpty(source)){
            return "0";
        }
        return source;
    }

    @Override
    public void savehddcGeomorphysvyregionServiceFromShpFiles(List<List<Object>> list, String provinceName, String cityName, String areaName,String savefilename) {
        if(list!=null&&list.size()>0){
            List<HddcGeomorphysvyregionEntity> datas= new ArrayList<>();
            for(int i=0;i<list.size();i++){
                List<Object> obs=list.get(i);
                HddcGeomorphysvyregionEntity data = new HddcGeomorphysvyregionEntity();
                data.setArea(areaName);
                data.setProvince(provinceName);
                data.setCity(cityName);
                data.setExtends8(savefilename);
                data.setId(obs.get(1).toString());
                data.setGeomorphysvyprjid(obs.get(2).toString());
                data.setFieldid(obs.get(3).toString());
                data.setName(obs.get(4).toString());
                data.setProfileAiid(obs.get(5).toString());
                data.setProfileArwid(obs.get(6).toString());
                data.setPhotoAiid(obs.get(7).toString());
                data.setPhotoArwid(obs.get(8).toString());
                data.setPhotoviewingto(Integer.valueOf(getStrBySourceStr(obs.get(8).toString())));
                data.setPhotographer(obs.get(9).toString());
                data.setCommentInfo(obs.get(10).toString());

                data.setCommentInfo(obs.get(5).toString());
                data.setExtends16("CGCS2000");
                String pstr=obs.get(0).toString();
                /*String[] ss1=pstr.split("\\(");
                if(ss1.length>=2){
                    String[] ss2=ss1[ss1.length-1].split("\\)");
                    if(ss2.length<=2){
                        String spacedata=ss2[0].replace(",",";").replace("; ",";").replace(" ",",");
                        data.setExtends5(spacedata);
                    }
                }*/
                pstr = pstr.replace(")), ((", "#");
                pstr = pstr.replace("), (", "#");
                String[] ss1=pstr.split("\\(");
                if(ss1.length>=2){
                    String[] ss2=ss1[ss1.length-1].split("\\)");
                    if(ss2.length<=2){
                        String spacedata=ss2[0].replace(",",";").replace("; ",";").replace(" ",",");
                        data.setExtends5(spacedata);
                    }
                }
                datas.add(data);
                /*for(int j=0;j<obs.size();j++){
                    Object value=obs.
                }*/
            }
            deleteByCreateUser(provinceName,cityName,areaName);
            saveHddcGeomorphysvyregionList(datas);
        }
    }


    public void deleteByCreateUser(String provinceName,String cityName,String areaName){
        String createID=PlatformSessionUtils.getUserId();
        List<HddcGeomorphysvyregionEntity> hddcGeomorphysvyregionList = this.hddcGeomorphysvyregionRepository.queryHddcGeomorphysvyregionByCreateuser(createID,provinceName,cityName,areaName);
        if(!PlatformObjectUtils.isEmpty(hddcGeomorphysvyregionList) && hddcGeomorphysvyregionList.size() > 0) {
            hddcGeomorphysvyregionRepository.deleteAll(hddcGeomorphysvyregionList);
        }
    }

    @Override
    public List<HddcGeomorphysvyregionEntity> findAll() {
        List<HddcGeomorphysvyregionEntity> list=this.hddcGeomorphysvyregionRepository.findAll();
        return list;
    }

    @Override
    @Transactional
    public void deleteFileData(SpaceDataParamsVo paramsVo) {
        String provinceName=paramsVo.getProvinceName();
        String cityName=paramsVo.getCityName();
        String areaName=paramsVo.getAreaName();
        String savefilename=paramsVo.getSavefilename();
        hddcGeomorphysvyregionRepository.deleteFileData(provinceName,cityName,areaName,savefilename);
    }
}
